<template>
  <div ref='stencilContainer' class='app-stencil'></div>
</template>

<script>
import { Addon } from '@antv/x6/lib/index'
// import { getCustomNodeTemplate } from '@/api/draw.js'
import RegisterUtil from '@/utils/graph-utils/registerUtil'
import ConfigUtil from '@/utils/graph-utils/configUtil'
import StencilUtil from '@/utils/graph-utils/stencilUtil'

export default {
  name: 'TemplatePanel',
  data() {
    return {}
  },
  mounted() {
    const self = this
    setTimeout(() => {
      self.initStencil()

      RegisterUtil.loadCustomizeNodes(self)
      // getCustomNodeTemplate().then(response => {
      //   const content = response.data
      //   if (content.length === 0) {
      //     return
      //   }
      //   const templdates = JSON.parse(content)
      //   for (const template of templdates) {
      //     // 注册节点
      //     RegisterUtil.registerNode2Graph(self, template.name, template)
      //   }
      // })
    }, 1000)
  },
  watch: {
    '$store.state.nodeModule.registerNodes': function(newVal) {
      const graph = this.$store.state.graphModule.graph
      const stencil = this.$store.state.graphModule.stencil
      const nodeGroups = new Map()
      for (const nodeConfig of newVal) {
        var node = graph.createNode({
          shape: nodeConfig.shape,
          x: 100,
          y: 100
        })
        const groupName = (nodeConfig.data && nodeConfig.data.group) ? nodeConfig.data.group : 'elecGroup'
        if (!nodeGroups.has(groupName)) {
          nodeGroups.set(groupName, [])
        }
        const stencilNode = StencilUtil.createStencilNode(node)
        nodeGroups.get(groupName).push(stencilNode)
      }
      for (const nodeGroup of nodeGroups) {
        stencil.load(nodeGroup[1], nodeGroup[0])
      }
    }
  },
  methods: {
    initStencil() {
      const graph = this.$store.state.graphModule.graph
      const stencilConfig = ConfigUtil.getDefaultStencilConfig()
      stencilConfig.target = graph
      // Stencil初始化
      const stencil = new Addon.Stencil(stencilConfig)

      // 挂载到页面
      this.$refs.stencilContainer.appendChild(stencil.container)

      const groupNodes = StencilUtil.getBaiscGroupNodes(graph)
      stencil.load(groupNodes, 'basicGroup')
      stencil.load([], 'elecGroup')

      this.$store.commit('setStencil', stencil)
    }
  }
}
</script>

<style scoped>
.app-stencil {
  width: 280px;
  height: 100%;
  border: 1px solid #f0f0f0;
  position: relative;
}

.x6-widget-stencil-group-content {
  background-color: #333b50;
}
</style>